<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { Form, FormItem, Input, RadioGroup } from 'ant-design-vue';
import { ImageUpload } from '#/components/upload';
import { pick } from 'lodash-es';
import {
  educationAdd,
  educationInfo,
  educationUpdate,
} from '#/api/knowledge/repository/education';
import type { EducationForm } from '#/api/knowledge/repository/education/model';
import { useBeforeCloseDiff } from '#/utils/popup';
import { Tinymce } from '#/components/tinymce';
import { getDictOptions } from '#/utils/dict';
import { useRoute } from 'vue-router';

const route = useRoute();
const knowledgeBaseId = route.params.id as string;

const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
/**
 * 定义默认值 用于reset
 */
const defaultValues: EducationForm = {
  knowledgeBaseId,
  id: undefined,
  title: undefined,
  content: undefined,
  format: 'IMAGE_TEXT',
  status: '1',
  coverImageUrl: '',
};

/**
 * 表单数据ref
 */
const formData = ref(defaultValues);

type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
  [key: string]: RuleObject[];
};
/**
 * 表单校验规则
 */
const formRules = ref<AntdFormRules<EducationForm>>({
  title: [{ required: true, message: $t('ui.formRules.required') }],
  content: [{ required: true, message: $t('ui.formRules.required') }],
  format: [{ required: true, message: $t('ui.formRules.selectRequired') }],
  status: [{ required: true, message: $t('ui.formRules.selectRequired') }],
  coverImageUrl: [
    { required: true, message: $t('ui.formRules.selectRequired') },
  ],
});

/**
 * useForm解构出表单方法
 */
const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

function customFormValueGetter() {
  return JSON.stringify(formData.value);
}

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: customFormValueGetter,
    currentGetter: customFormValueGetter,
  },
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[800px]',
  fullscreenButton: true,
  fullscreen: true,
  closeOnClickModal: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;
    if (isUpdate.value && id) {
      const record = await educationInfo(id);
      // 只赋值存在的字段
      const filterRecord = pick(record, Object.keys(defaultValues));
      formData.value = filterRecord;
    }
    await markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    await validate();
    // 可能会做数据处理 使用cloneDeep深拷贝
    const data = cloneDeep(formData.value);
    await (isUpdate.value ? educationUpdate(data) : educationAdd(data));
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleClosed() {
  formData.value = defaultValues;
  resetFields();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title">
    <Form layout="vertical">
      <FormItem label="标题" v-bind="validateInfos.title">
        <Input
          :placeholder="$t('ui.formRules.required')"
          v-model:value="formData.title"
        />
      </FormItem>
      <div class="grid sm:grid-cols-1 lg:grid-cols-2">
        <FormItem label="形式" v-bind="validateInfos.format">
          <RadioGroup
            button-style="solid"
            option-type="button"
            v-model:value="formData.format"
            :options="getDictOptions('know_edu_type')"
          />
        </FormItem>
        <FormItem label="封面" v-bind="validateInfos.coverImageUrl">
          <ImageUpload v-model:value="formData.coverImageUrl" :max-count="1" />
          <!-- <ImageUploadOld v-model:value="formData.coverImageUrl" :resultField="'url'" :maxNumber="3" /> -->
        </FormItem>
      </div>
      <div class="grid sm:grid-cols-1 lg:grid-cols-2">
        <FormItem label="状态" v-bind="validateInfos.status">
          <RadioGroup
            button-style="solid"
            option-type="button"
            v-model:value="formData.status"
            :options="[
              {
                label: '启用',
                value: '1',
              },
              {
                label: '禁用',
                value: '0',
              },
            ]"
          />
        </FormItem>
      </div>
      <FormItem label="知识库内容" v-bind="validateInfos.content">
        <Tinymce v-model="formData.content" />
      </FormItem>
    </Form>
  </BasicModal>
</template>
